package com.nf.entity;


import com.nf.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import javax.persistence.Query;
import java.util.List;

public class Test {
    public static void main(String[] args){
        List<Student> studentList=null;
        //第一步：需要一个配置类
        Configuration cfg = new Configuration();
        //第二步：对配置类加载一个配置文件
        cfg.configure();
        //config.configure("/hibernate.cfg.xml");
        SessionFactory factory = cfg.buildSessionFactory();
         //获取一个session
        Session session=factory.openSession();//opensession:打开一个cmd窗口
        Transaction tx=session.beginTransaction();//开启事物
        //一.添加记录
       /* Student student=new Student();
        student.setName("将军");
        student.setSex("男");
        session.save(student);//把数据存放到session中
        tx.commit();*/
       //二.查询记录
        //Query query = session.createQuery("from Student ");//1.查询全部记录
       Student ss = session.get(Student.class,3);//从session中取出第x条记录查询
        //Student.class =>  select*from t_student where id=1;
        System.out.println(ss);
       // studentList = query.getResultList();
        tx.commit();
       //三.修改记录
        /*Student ss = session.get(Student.class,6);//查询这一条来修改
        ss.setName("张高丽"); //向返回的ss对象里面设置修改之后的值
        ss.setSex("男");
        session.update(ss);//sessin.save();此方法也行
        tx.commit();*/  //此处才是真正与数据库交互的语句

        //四.删除记录
       /* Student ss = session.get(Student.class,6);
        session.delete(ss);
        tx.commit();*/
        //第二种删除方法
        /*Student ss = new Student();
        ss.setId(5);
        session.delete(ss);
        tx.commit();*/
        //事物回滚
       /* try{
            Student student1=session.get(Student.class,1);
            Student student2=session.get(Student.class,2);
            student1.setSex("女");
            student2.setSex("外星人没有性别");
            session.update(student1);
            session.update(student2);
            tx.commit();
        }catch(Exception e){

            System.out.println("发生异常:"+e.getMessage());
            tx.rollback();
        }*/

        session.close();
        factory.close();

        System.out.println("你好！");
        System.out.println(factory);


    }
}
